//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Definitions;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Security.Permissions;
using DotNetNuke.Services.EventQueue;
using DotNetNuke.Services.Installer.Packages;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.WebControls;
namespace DotNetNuke.Modules.Admin.Features
{
	partial class ModuleEditor : PackageEditorBase
	{
		private DesktopModuleInfo _DesktopModule = null;
		private ModuleDefinitionInfo _ModuleDefinition = null;
		protected DesktopModuleInfo DesktopModule {
			get {
				if (_DesktopModule == null) {
					_DesktopModule = DesktopModuleController.GetDesktopModuleByPackageID(PackageID);
				}
				return _DesktopModule;
			}
		}
		protected override string EditorID {
			get { return "ModuleEditor"; }
		}
		protected bool IsAddDefinitionMode {
			get {
				bool _IsAddDefinitionMode = Null.NullBoolean;
				if (ViewState["IsAddDefinitionMode"] != null) {
					_IsAddDefinitionMode = Convert.ToBoolean(ViewState["IsAddDefinitionMode"]);
				}
				return _IsAddDefinitionMode;
			}
			set { ViewState["IsAddDefinitionMode"] = value; }
		}
		protected int ModuleDefinitionID {
			get {
				int _ModuleDefinitionID = Null.NullInteger;
				if (ViewState["ModuleDefinitionID"] != null) {
					_ModuleDefinitionID = Convert.ToInt32(ViewState["ModuleDefinitionID"]);
				}
				return _ModuleDefinitionID;
			}
			set { ViewState["ModuleDefinitionID"] = value; }
		}
		protected ModuleDefinitionInfo ModuleDefinition {
			get {
				if (_ModuleDefinition == null) {
					_ModuleDefinition = ModuleDefinitionController.GetModuleDefinitionByID(ModuleDefinitionID);
				}
				return _ModuleDefinition;
			}
		}
		private void BindDefinition()
		{
			ctlDefinition.LocalResourceFile = LocalResourceFile;
			if (IsAddDefinitionMode) {
				ModuleDefinitionInfo definition = new ModuleDefinitionInfo();
				definition.DesktopModuleID = DesktopModule.DesktopModuleID;
				definition.ModuleDefID = Null.NullInteger;
				ctlDefinition.DataSource = definition;
				ctlDefinition.DataBind();
				cmdDeleteDefinition.Visible = false;
				cmdUpdateDefinition.Text = Localization.GetString("cmdCreateDefinition", LocalResourceFile);
				pnlDefinition.Visible = true;
				pnlControls.Visible = false;
			} else {
				if (ModuleDefinition != null && ModuleDefinition.DesktopModuleID == DesktopModule.DesktopModuleID) {
					ctlDefinition.DataSource = ModuleDefinition;
					ctlDefinition.DataBind();
					cmdDeleteDefinition.Visible = true;
					cmdUpdateDefinition.Text = Localization.GetString("cmdUpdateDefinition", LocalResourceFile);
					if (!Page.IsPostBack) {
						Localization.LocalizeDataGrid(ref grdControls, LocalResourceFile);
					}
					grdControls.DataSource = ModuleDefinition.ModuleControls.Values;
					grdControls.DataBind();
					pnlDefinition.Visible = true;
					pnlControls.Visible = true;
				} else {
					pnlDefinition.Visible = false;
				}
			}
		}
		private void BindDesktopModule(bool refreshDefinitions)
		{
			if (DesktopModule != null) {
				ctlDesktopModule.LocalResourceFile = LocalResourceFile;
				ctlDesktopModule.DataSource = DesktopModule;
				ctlDesktopModule.DataBind();
				fldIsPremium.Visible = !DesktopModule.IsAdmin;
				if (!Page.IsPostBack) {
					if ((Request.QueryString["ModuleDefinitionID"] != null)) {
						ModuleDefinitionID = Int32.Parse(Request.QueryString["ModuleDefinitionID"]);
					}
				}
				if (!Page.IsPostBack || refreshDefinitions)
				{
					cboDefinitions.DataSource = DesktopModule.ModuleDefinitions.Values;
					cboDefinitions.DataBind();
					if (ModuleDefinitionID == Null.NullInteger && cboDefinitions.Items.Count > 0) {
						ModuleDefinitionID = int.Parse(cboDefinitions.SelectedValue);
					}
					if (ModuleDefinitionID != Null.NullInteger) {
						ListItem selectedDefinition = cboDefinitions.Items.FindByValue(ModuleDefinitionID.ToString());
						if (selectedDefinition != null) {
							cboDefinitions.SelectedIndex = -1;
							selectedDefinition.Selected = true;
						}
					}
				}
				if (!IsSuperTab) {
					BindPermissions();
				} else {
					pnlPermissions.Visible = false;
				}
				BindPortalDesktopModules();
				BindDefinition();
				lblDefinitionError.Visible = false;
			}
		}
		private void BindPermissions()
		{
			PortalDesktopModuleInfo portalModule = DesktopModuleController.GetPortalDesktopModule(ModuleContext.PortalSettings.PortalId, DesktopModule.DesktopModuleID);
			if (portalModule != null) {
				dgPermissions.PortalDesktopModuleID = portalModule.PortalDesktopModuleID;
				bool isVisible = DesktopModulePermissionController.HasDesktopModulePermission(DesktopModulePermissionController.GetDesktopModulePermissions(portalModule.PortalDesktopModuleID), "DEPLOY") || ModuleContext.PortalSettings.UserInfo.IsInRole(ModuleContext.PortalSettings.AdministratorRoleName) || ModuleContext.PortalSettings.UserInfo.IsSuperUser;
				pnlPermissions.Visible = isVisible;
				if (!isVisible) {
					lblHelp.Text = Localization.GetString("NoPermission", LocalResourceFile);
				}
			}
		}
		private void BindPortalDesktopModules()
		{
			PortalController objPortals = new PortalController();
			ArrayList arrPortals = objPortals.GetPortals();
			Dictionary<int, PortalDesktopModuleInfo> dicPortalDesktopModules = DesktopModuleController.GetPortalDesktopModulesByDesktopModuleID(DesktopModule.DesktopModuleID);
			foreach (PortalDesktopModuleInfo objPortalDesktopModule in dicPortalDesktopModules.Values) {
				foreach (PortalInfo objPortal in arrPortals) {
					if (objPortal.PortalID == objPortalDesktopModule.PortalID) {
						arrPortals.Remove(objPortal);
						break;
					}
				}
			}
			ctlPortals.AvailableDataSource = arrPortals;
			ctlPortals.SelectedDataSource = dicPortalDesktopModules.Values;
			ctlPortals.Visible = !DesktopModule.IsAdmin;
		}
		private void UpdateModuleInterfaces(string BusinessControllerClass)
		{
			DotNetNuke.Services.EventQueue.EventMessage oAppStartMessage = new DotNetNuke.Services.EventQueue.EventMessage();
			oAppStartMessage.Sender = ModuleContext.PortalSettings.UserInfo.Username;
			oAppStartMessage.Priority = MessagePriority.High;
			oAppStartMessage.ExpirationDate = DateTime.Now.AddYears(-1);
			oAppStartMessage.SentDate = System.DateTime.Now;
			oAppStartMessage.Body = "";
			oAppStartMessage.ProcessorType = "DotNetNuke.Entities.Modules.EventMessageProcessor, DotNetNuke";
			oAppStartMessage.ProcessorCommand = "UpdateSupportedFeatures";
			oAppStartMessage.Attributes.Add("BusinessControllerClass", BusinessControllerClass);
			oAppStartMessage.Attributes.Add("DesktopModuleId", DesktopModule.DesktopModuleID.ToString());
			EventQueueController.SendMessage(oAppStartMessage, "Application_Start");
			DotNetNuke.Common.Utilities.Config.Touch();
		}
		protected override void OnInit(System.EventArgs e)
		{
			base.OnInit(e);

            cmdAddControl.Click += new EventHandler(cmdAddControl_Click);
            cmdAddDefinition.Click += new EventHandler(cmdAddDefinition_Click);
            cmdDeleteDefinition.Click += new EventHandler(cmdDeleteDefinition_Click);
            cmdUpdate.Click += new EventHandler(cmdUpdate_Click);
            cmdUpdateDefinition.Click += new EventHandler(cmdUpdateDefinition_Click);
            ctlPortals.AddButtonClick += new DualListBoxEventHandler(ctlPortals_AddButtonClick);
            ctlPortals.AddAllButtonClick += new EventHandler(ctlPortals_AddAllButtonClick);
            ctlPortals.RemoveAllButtonClick += new EventHandler(ctlPortals_RemoveAllButtonClick);
            ctlPortals.RemoveButtonClick += new DualListBoxEventHandler(ctlPortals_RemoveButtonClick);
            grdControls.DeleteCommand += new DataGridCommandEventHandler(grdControls_DeleteCommand);
            grdControls.ItemDataBound += new DataGridItemEventHandler(grdControls_ItemDataBound);

			if (IsSuperTab) {
				lblHelp.Text = Localization.GetString("HostHelp", LocalResourceFile);
			} else {
				lblHelp.Text = Localization.GetString("AdminHelp", LocalResourceFile);
			}
			foreach (DataGridColumn column in grdControls.Columns) {
				if (object.ReferenceEquals(column.GetType(), typeof(ImageCommandColumn))) {
					ImageCommandColumn imageColumn = (ImageCommandColumn)column;
					if (imageColumn.CommandName == "Delete") {
						imageColumn.OnClickJS = Localization.GetString("DeleteItem");
					}
				}
			}
		}
		protected override void OnLoad(System.EventArgs e)
		{
			base.OnLoad(e);
			ctlPortals.LocalResourceFile = LocalResourceFile;
			UI.Utilities.ClientAPI.AddButtonConfirm(cmdDeleteDefinition, Services.Localization.Localization.GetString("DeleteItem"));
		}
		protected override void OnPreRender(System.EventArgs e)
		{
			base.OnPreRender(e);
			pnlHelp.Visible = !IsWizard;
			pnlDefinitions.Visible = (!IsWizard) && IsSuperTab;
			cmdUpdate.Visible = (!IsWizard) && (!IsSuperTab && pnlPermissions.Visible);
			ctlPortals.Visible = !IsWizard;
		}
		public override void Initialize()
		{
			pnlDesktopModule.Visible = IsSuperTab;
			BindDesktopModule(false);
		}
		public override void UpdatePackage()
		{
			bool bUpdateSupportedFeatures = Null.NullBoolean;
			PackageInfo _Package = PackageController.GetPackage(PackageID);
			if (ctlDesktopModule.IsValid) {
				DesktopModuleInfo desktopModule = ctlDesktopModule.DataSource as DesktopModuleInfo;
				if (desktopModule != null && _Package != null) {
					desktopModule.FriendlyName = _Package.FriendlyName;
					desktopModule.Version = Common.Globals.FormatVersion(_Package.Version);
					if (string.IsNullOrEmpty(desktopModule.BusinessControllerClass)) {
						desktopModule.SupportedFeatures = 0;
					} else {
						bUpdateSupportedFeatures = true;
					}
					DesktopModuleController.SaveDesktopModule(desktopModule, false, true);
				}
			}
			if (bUpdateSupportedFeatures) {
				UpdateModuleInterfaces(DesktopModule.BusinessControllerClass);
			}
		}
		protected void cboDefinitions_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			if (!IsAddDefinitionMode) {
				ModuleDefinitionID = int.Parse(cboDefinitions.SelectedValue);
				_ModuleDefinition = null;
				BindDefinition();
			}
		}
		protected void cmdAddControl_Click(object sender, System.EventArgs e)
		{
			Response.Redirect(ModuleContext.EditUrl("ModuleControlID", "-1", "EditControl", "packageId=" + PackageID.ToString(), "moduledefid=" + ModuleDefinition.ModuleDefID.ToString()), true);
		}
		protected void cmdAddDefinition_Click(object sender, System.EventArgs e)
		{
			IsAddDefinitionMode = true;
			ModuleDefinitionID = Null.NullInteger;
			_ModuleDefinition = null;
			BindDefinition();
		}
		protected void cmdDeleteDefinition_Click(object sender, System.EventArgs e)
		{
			ModuleDefinitionController objModuleDefinitions = new ModuleDefinitionController();
			objModuleDefinitions.DeleteModuleDefinition(ModuleDefinitionID);
			ModuleDefinitionID = Null.NullInteger;
			_ModuleDefinition = null;
			_DesktopModule = null;
			BindDesktopModule(true);
		}
		private void cmdUpdate_Click(object sender, System.EventArgs e)
		{
			bool bUpdateSupportedFeatures = Null.NullBoolean;
			if (this.ModuleContext.PortalSettings.ActiveTab.IsSuperTab) {
				UpdatePackage();
			} else {
				Security.Permissions.DesktopModulePermissionCollection objCurrentPermissions;
				objCurrentPermissions = DesktopModulePermissionController.GetDesktopModulePermissions(dgPermissions.PortalDesktopModuleID);
				if (!objCurrentPermissions.CompareTo(dgPermissions.Permissions)) {
					DesktopModulePermissionController.DeleteDesktopModulePermissionsByPortalDesktopModuleID(dgPermissions.PortalDesktopModuleID);
					foreach (DesktopModulePermissionInfo objPermission in dgPermissions.Permissions) {
						DesktopModulePermissionController.AddDesktopModulePermission(objPermission);
					}
				}
				DataCache.RemoveCache(string.Format(DataCache.PortalDesktopModuleCacheKey, this.ModuleContext.PortalId.ToString()));
				dgPermissions.ResetPermissions();
			}
		}
		protected void cmdUpdateDefinition_Click(object sender, System.EventArgs e)
		{
			if (ctlDefinition.IsValid && ctlDefinition.IsDirty) {
				ModuleDefinitionInfo definition = ctlDefinition.DataSource as ModuleDefinitionInfo;
				if (definition != null) {
					if ((IsAddDefinitionMode && ModuleDefinitionController.GetModuleDefinitionByFriendlyName(definition.FriendlyName) == null) || (!IsAddDefinitionMode)) {
						ModuleDefinitionID = ModuleDefinitionController.SaveModuleDefinition(definition, false, true);
						IsAddDefinitionMode = false;
						_DesktopModule = null;
						BindDesktopModule(true);
					} else {
						lblDefinitionError.Visible = true;
					}
				}
			}
		}
		protected void ctlPortals_AddAllButtonClick(object sender, System.EventArgs e)
		{
			PortalController objPortals = new PortalController();
			foreach (PortalInfo objPortal in objPortals.GetPortals()) {
				DesktopModuleController.AddDesktopModuleToPortal(objPortal.PortalID, DesktopModule.DesktopModuleID, true, false);
			}
			DataCache.ClearHostCache(true);
			BindDesktopModule(false);
		}
		protected void ctlPortals_AddButtonClick(object sender, UI.WebControls.DualListBoxEventArgs e)
		{
			if (e.Items != null) {
				foreach (string portal in e.Items) {
					DesktopModuleController.AddDesktopModuleToPortal(int.Parse(portal), DesktopModule.DesktopModuleID, true, false);
				}
			}
			DataCache.ClearHostCache(true);
			BindDesktopModule(false);
		}
		protected void ctlPortals_RemoveAllButtonClick(object sender, System.EventArgs e)
		{
			PortalController objPortals = new PortalController();
			foreach (PortalInfo objPortal in objPortals.GetPortals()) {
				DesktopModuleController.RemoveDesktopModuleFromPortal(objPortal.PortalID, DesktopModule.DesktopModuleID, false);
			}
			DataCache.ClearHostCache(true);
			BindDesktopModule(false);
		}
		protected void ctlPortals_RemoveButtonClick(object sender, UI.WebControls.DualListBoxEventArgs e)
		{
			if (e.Items != null) {
				foreach (string portal in e.Items) {
					DesktopModuleController.RemoveDesktopModuleFromPortal(int.Parse(portal), DesktopModule.DesktopModuleID, false);
				}
			}
			DataCache.ClearHostCache(true);
			BindDesktopModule(false);
		}
		protected void grdControls_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			int controlID = Int32.Parse(e.CommandArgument.ToString());
			ModuleControlController.DeleteModuleControl(controlID);
			_ModuleDefinition = null;
			BindDefinition();
		}
		protected void grdControls_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
		{
			DataGridItem item = e.Item;
			if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem)
			{
				HyperLink editHyperlink = item.Controls[0].Controls[0] as HyperLink;
				if (editHyperlink != null) {
					editHyperlink.NavigateUrl = ModuleContext.EditUrl("ModuleControlID", editHyperlink.NavigateUrl, "EditControl", "packageId=" + PackageID.ToString(), "moduledefid=" + ModuleDefinition.ModuleDefID.ToString());
				}
			}
		}
	}
}
